package com.example.springblog.controller;

import com.example.springblog.Utils.JWTUtils;
import com.example.springblog.Utils.MD5Utils;
import com.example.springblog.constant.Constants;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.UserService;
import io.jsonwebtoken.lang.Strings;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    //注入查找的user服务层
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String username, String password){
        //校验输入的数据是否为空
        if(!Strings.hasLength(username) || !Strings.hasLength(password)){
            return Result.fail("输入不能为空");
        }

        UserInfo userInfo=userService.selectByName(username);
        if(userInfo == null){
            return Result.fail("用户不存在");
        }

        if(!MD5Utils.verify(password,userInfo.getPassword())){
            return Result.fail("密码错误");
        }

        //如果这里的输入是正确的，那么就可以返回令牌了
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.ID, userInfo.getId());
        claim.put(Constants.USER_NAME, userInfo.getUserName());
        //创建一个令牌
        String token = JWTUtils.genJWT(claim);
        return Result.success(token);
    }

    /**
     * 根据登录获取用户信息
     * @param request
     * @return
     */
    @RequestMapping("getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String token = request.getHeader(Constants.USER_TOKEN_HEADER);

        Integer id = JWTUtils.getIDByToken(token);
        if(id == null){
            return null;
        }
        UserInfo userInfo = userService.selectById(id);
        return  userInfo;
    }

    /**
     * 根据博客ID获取作者信息
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        //进行输入的ID是否合理
        if(blogId == null){
            return null;
        }
        UserInfo userInfo = userService.selectByBlogId(blogId);

        return userInfo;
    }
}
